import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:video_player/video_player.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:xvideos/hj_page/video/cartoon/video_cartoon_info_widget.dart';
import 'package:xvideos/hj_page/video/view/video_detail_bottom_menu.dart';
import 'package:xvideos/hj_utils/api_service/acg_service.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/banner/ads_grid_view_widget.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';

import '../../../hj_model/acg/comic_chapters_model.dart';
import '../../../hj_model/cartoon_media_info.dart';
import '../../../tools_base/loading/loading_center_widget.dart';
import '../../../tools_base/refresh/pull_refresh.dart';
import '../../cartoon_business/cartoon_detail_page.dart';
import '../../cartoon_business/novel_detail_page.dart';
import 'cartoon_episode_menu_alert.dart';

class VideoDetailCartoonView extends StatefulWidget {
  final VideoModel? model;
  final ComicChapterInfo? currentEpisode;
  final VideoPlayerController? controller;
  final Function? callback;
  final Function(VideoModel model)? vmCallback;
  final Function(ComicChapterInfo model)? episoCallback; //动漫选集回掉
  const VideoDetailCartoonView({
    super.key,
    this.model,
    this.controller,
    this.callback,
    this.vmCallback,
    this.currentEpisode,
    this.episoCallback,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoDetailCartoonViewState();
  }
}

class _VideoDetailCartoonViewState extends State<VideoDetailCartoonView> with AutomaticKeepAliveClientMixin {
  RefreshController? refreshController;

  VideoPlayerController? get vpController => widget.controller;

  VideoModel? get videoModel => widget.model;

  bool get hasFollowed => videoModel?.publisher?.hasFollowed ?? false;
  List<CartoonMediaInfo>? moreWorks;
  int currentPage = 1;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    if (moreWorks?.isNotEmpty != true) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        safeFlashUI();
        _loadData();
      });
    }
  }

  Future<bool> safeFlashUI() async {
    if (!mounted) return false;
    if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.idle) {
      await SchedulerBinding.instance.endOfFrame;
      if (!mounted) return false;
    }
    setState(() {});
    return true;
  }

  bool isLoading = false;

  void _loadData({
    int page = 1,
    int size = 12,
  }) async {
    try {
      if (isLoading) return;
      isLoading = true;
      final retRep = await ACGService.comicsRecommendList(
        page,
        size,
        mediaId: widget.model?.id ?? '',
      );
      currentPage = page;
      moreWorks ??= [];
      if (page == 1) {
        moreWorks?.clear();
      }
      moreWorks?.addAll(retRep?.list ?? []);
      if (retRep?.hasNext == true) {
        refreshController?.loadComplete();
      } else {
        refreshController?.loadNoData();
      }
    } catch (e) {
      refreshController?.loadComplete();
      moreWorks ??= [];
    }
    isLoading = false;
    safeFlashUI();
  }

  void moreMovieEvent(CartoonMediaInfo model) {
    widget.controller?.pause();
    if (model.mediaType == 'image') {
      //跳转到动漫情页
      Get.to(
          () => CartoonDetailPage(
                id: model.id ?? '',
              ),
          preventDuplicates: false);
    } else if (model.mediaType == 'text') {
      //跳转到小说详情
      Get.toNamed(
        NovelDetailPage.routeName,
        arguments: model.id,
        preventDuplicates: false,
      );
    } else {
      VideoModel vmodel = VideoModel();
      vmodel.id = model.id;
      vmodel.cover = model.coverH;
      vmodel.videoType = 1;
      widget.vmCallback?.call(vmodel);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return pullYsRefresh(
      onInit: (ctr) => refreshController = ctr,
      enablePullDown: false,
      onLoading: (refreshController) => _loadData(page: currentPage + 1),
      child: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Container(
              padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
              child: VideoDetailCartoonInfoWidget(
                model: videoModel,
                controller: widget.controller,
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              padding: const EdgeInsets.only(top: 18),
              margin: EdgeInsets.only(left: 12, right: 12),
              child: VideoDetailBottomMenu(model: videoModel),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.fromLTRB(12, 18, 12, 18),
              child: 0.5.line,
            ),
          ),
          SliverToBoxAdapter(
            child: VideoCartoonEpisodeMenu(
              widget.currentEpisode,
              cartoonModel: videoModel?.mediaInfo,
              callback: widget.episoCallback,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.fromLTRB(12, 18, 12, 18),
              child: 0.5.line,
            ),
          ),
          SliverToBoxAdapter(
            child: AdsGridViewWidget(
              6,
              padding: EdgeInsets.only(left: 12, bottom: 18),
              horCount: 5.3,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.only(left: 12),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "猜你喜欢",
                    style: TextStyle(
                      color: Color(0xE5FFFFFF),
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const Spacer(),
                ],
              ),
            ),
          ),
          _buildMoreVideo(),
        ],
      ),
    );
  }

  Widget _buildMoreVideo() {
    if (moreWorks == null) {
      return const SliverToBoxAdapter(
        child: SizedBox(
          height: 200,
          child: LoadingCenterWidget(),
        ),
      );
    } else if (moreWorks?.isEmpty == true) {
      return SliverToBoxAdapter(
        child: SizedBox(
          height: 200,
          child: CErrorWidget(
            retryOnTap: () {
              moreWorks = null;
              safeFlashUI();
              _loadData();
            },
          ),
        ),
      );
    } else {
      return SliverPadding(
        padding: EdgeInsets.fromLTRB(12, 12, 12, 0),
        sliver: SliverGrid(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 12,
            crossAxisSpacing: 6,
            childAspectRatio: 111 / 190, //子控件宽高比
          ),
          delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              CartoonMediaInfo model = moreWorks![index];
              return AcgItemWidget(
                info: model,
                tapCallback: () {
                  VideoModel videoModel = VideoModel(id: model.id);
                  videoModel.cover = model.coverV ?? model.coverH ?? "";
                  widget.vmCallback?.call(videoModel);
                },
              );
            },
            childCount: moreWorks?.length ?? 0,
          ),
        ),
      );
    }
  }
}

class VideoCartoonEpisodeMenu extends StatelessWidget {
  final CartoonMediaInfo? cartoonModel;
  final ComicChapterInfo? currentEpisode;
  final Function(ComicChapterInfo model)? callback;

  const VideoCartoonEpisodeMenu(
    this.currentEpisode, {
    super.key,
    this.cartoonModel,
    this.callback,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 12),
      child: StatefulBuilder(builder: (ctx, states) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            GestureDetector(
              onTap: () async {
                await Get.bottomSheet(CartoonEpisodeMenuAlert(
                  currentEpisode,
                  cartoonModel: cartoonModel,
                  callback: (index) {
                    callback?.call(index);
                  },
                ));
                states(() {});
              },
              child: Row(
                children: [
                  Text(
                    "选集",
                    style: TextStyle(
                      fontSize: 18,
                      color: Color(0xE5FFFFFF),
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const Spacer(),
                  Text(
                    "全${cartoonModel?.totalEpisode ?? 1}话",
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0xff989898),
                    ),
                  ),
                  3.sizeBoxW,
                  Icon(
                    Icons.arrow_forward_ios_rounded,
                    color: Color(0xff989898),
                    size: 13,
                  ),
                  16.sizeBoxW,
                ],
              ),
            ),
            const SizedBox(height: 12),
            SizedBox(
              height: 58,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                padding: EdgeInsets.zero,
                itemCount: cartoonModel?.episodeList?.length ?? 0,
                itemBuilder: (context, index) {
                  ComicChapterInfo model = cartoonModel!.episodeList![index];
                  return Container(
                    width: 58,
                    height: 58,
                    margin: const EdgeInsets.only(right: 10),
                    child: GestureDetector(
                      onTap: () => callback?.call(model),
                      child: CartoonChapterItem(
                        model,
                        isSelected: currentEpisode?.id == model.id,
                        isFirst: index == 0,
                        fatherM: cartoonModel!,
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        );
      }),
    );
  }
}
